import {  getToken, loginPass, sentYzm, YZYzm } from '@/api/login';
import { ShowFail } from '@/utils/message';
import { reg } from '@/utils/reg';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
  ProConfigProvider,
} from '@ant-design/pro-components';
import { useRequest, useLocalStorageState } from 'ahooks';
import { message, Space, Tabs, Form, Button } from 'antd';
import { CSSProperties, useEffect, useRef } from 'react';
import { useState } from 'react';
import { Link, history } from 'umi';

type LoginType = 'phone' | 'account';

const iconStyles: CSSProperties = {
  marginInlineStart: '16px',
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '24px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

export default () => {
  const [loginType, setLoginType] = useState<LoginType>('account');
  const [form] = Form.useForm()
  const formRef = useRef<any>()
  const [proAccount, setProAccount] = useLocalStorageState<string | undefined>(
    'calAccount',
  )
  const [proPass, setProPass] = useLocalStorageState<string | undefined>(
    'calPass',
  )
  const [proPhone, setProPhone] = useLocalStorageState<string | undefined>(
    'cPhone',
  )
  const [proToken, setProToken] = useLocalStorageState<string | undefined>(
    'calToken',
  )
  const [proRemeber, setProRemeber] = useLocalStorageState<boolean | undefined>(
    'calRemeber',
  )
  const todoLogin = useRequest(loginPass, {
    manual: true,
    onSuccess: (res:loginUsers) => {
      console.log(res)
      if (res.code == 200) {
        setProToken(res.token)
        setProAccount(form.getFieldValue('account'))
        if (form.getFieldValue("autoLogin")) { 
          setProRemeber(form.getFieldValue('autoLogin'))
          setProPass(form.getFieldValue('password'))
        } else {
          setProRemeber(false)
          setProPass('')
        }
        history.push("/admin")
      }
    }
  })

  // 发送验证码
  const todoSentCaptcha = useRequest(sentYzm, {
    manual: true,
    onSuccess: (res: any, params) => {
        
    }
  })

  const todoCheckCaptcha = useRequest(YZYzm, {
    manual: true,
    onSuccess: (res:YzmTypes) => {
      if (res.code == 200) {
        // 获取 token  //登录 
        todoGetToken.run(form.getFieldValue('phone'))
      }
    }
  })

  const todoGetToken = useRequest(getToken,{
    manual:true,
    onSuccess:(res:tokenType)=>{
        if(res.code==200){
            setProToken(res.token)
            setProPhone(form.getFieldValue('phone'))
            history.push("/admin")
        }
    }
  })


  // 提交表单
  const onFinish = async (value:any) => {
    console.log(value)
    if (loginType == 'account') {
      todoLogin.run(form.getFieldValue("account"),form.getFieldValue('password'))
    } else {
        todoCheckCaptcha.run(form.getFieldValue("phone"),form.getFieldValue("captcha"))
    }
  }

  useEffect(() => {
    form.setFieldValue('account', proAccount)
    form.setFieldValue('phone', proPhone)
    if (proRemeber) {
      form.setFieldValue('autoLogin', proRemeber)
      form.setFieldValue('password', proPass)

    }
  }, [])
  return (
    <div style={{ overflow: 'hidden' }}>
      <div style={{ marginTop: 120 }}>
        <ProConfigProvider hashed={false}>
          <div style={{ backgroundColor: 'white' }}>
            <LoginForm
              form={form}
              formRef={formRef}
              logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
              title="面试平台"
              subTitle="后台管理系统"
              actions={
                <Space>
                  其他登录方式
                  <AlipayCircleOutlined style={iconStyles} />
                  <TaobaoCircleOutlined style={iconStyles} />
                  <WeiboCircleOutlined style={iconStyles} />
                </Space>
              }
              onFinish={onFinish}
              onFinishFailed={() => ShowFail('校验失败')}

              submitter={{
                // 配置按钮文本
                // searchConfig: {
                //   resetText: '重置',
                //   submitText: '提交1111',
                // },
                // // 配置按钮的属性
                // resetButtonProps: {
                //   style: {
                //     // 隐藏重置按钮
                //     display: 'none',
                //   },
                // },
                // submitButtonProps: {
                //   style:{
                //     display:"block"
                //   }
                // },
                // 完全自定义整个区域
                render: (props: any, doms: any) => {
                  // console.log(props);
                  // return <div>{doms}</div>
                  return [
                    <div>
                      {/* onClick={() => props.form?.submit?.()} */}
                      <Button type="primary" block key="submit"
                        onClick={() => formRef.current?.submit()}
                      >
                        提交
                      </Button>
                      <Button block danger style={{ marginTop: 10 }} key="rest" onClick={() => formRef.current?.resetFields()}>
                        重置
                      </Button>
                    </div>
                  ];
                },
              }}
            >
              <Tabs
                centered
                activeKey={loginType}
                onChange={(activeKey) => setLoginType(activeKey as LoginType)}
              >
                <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
                <Tabs.TabPane key={'phone'} tab={'手机号登录'} />
              </Tabs>
              {loginType === 'account' && (
                <>
                  <ProFormText
                    name="account"
                    fieldProps={{
                      size: 'large',
                      prefix: <UserOutlined className={'prefixIcon'} />,
                    }}
                    placeholder={'账号: uesrname or phone'}
                    rules={[
                      {
                        required: true,
                        message: '请输入账户信息',
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={'prefixIcon'} />,
                    }}
                    placeholder={'密码: 6-16数字字母组合'}
                    rules={[
                      {
                        required: true,
                        message: '请输入密码！',
                      },
                      {
                        pattern: reg.pwd,
                        message: '密码格式不正确'
                      }
                    ]}
                  />
                </>
              )}
              {loginType === 'phone' && (
                <>
                  <ProFormText
                    fieldProps={{
                      size: 'large',
                      prefix: <MobileOutlined className={'prefixIcon'} />,
                    }}
                    name="phone"
                    placeholder={'手机号'}
                    rules={[
                      {
                        required: true,
                        message: '请输入手机号！',
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '手机号格式错误！',
                      },
                    ]}
                  />
                  <ProFormCaptcha
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={'prefixIcon'} />,
                    }}
                    captchaProps={{
                      size: 'large',
                    }}
                    countDown={180}
                    phoneName="phone"
                    placeholder={'请输入验证码'}
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `倒计时 ${count} S`;
                      }
                      return '获取验证码';
                    }}
                    name="captcha"
                    rules={[
                      {
                        required: true,
                        message: '请输入验证码！',
                      },
                      {
                        pattern: reg.code,
                        message: '4位数字验证码'
                      }
                    ]}
                    onGetCaptcha={async (phone) => {
                      todoSentCaptcha.run(form.getFieldValue("phone"))
                    }}
                  />
                </>
              )}
              <div
                style={{
                  marginBlockEnd: 24,
                }}
              >
                {
                  loginType == 'account' && <ProFormCheckbox noStyle name="autoLogin">
                    记住密码
                  </ProFormCheckbox>
                }
                <Link
                  style={{
                    float: 'right',
                    marginBottom: 10,
                  }}
                  to='/findpass'
                >
                  忘记密码
                </Link>
              </div>
            </LoginForm>
          </div>
        </ProConfigProvider>
      </div>
    </div>
  );
};